<script setup lang="ts">
import Head from '@/views/head.vue'
import Main from '@/views/main.vue'
import {useCounterStore} from '@/stores/counter.ts'
import {nextTick, onMounted, reactive, ref} from "vue";
import {Close} from "@element-plus/icons-vue";
import SvgIcon from "@/components/SvgIcon/index.vue";
import {ElMessage, ElNotification} from "element-plus";
import {save,page} from '@/api/chat.ts'
import {add} from '@/api/uv.ts'
import {savePersonalInfoReservation} from '@/api/personalInfoReservation.ts'
import qq from '@/assets/icons/qq.jpg'
import weixin from '@/assets/icons/weixin.jpg'
import {list} from "@/api/contact-us.ts";
const contactus=ref()
const getContactUs=()=>{
  list({}).then((res)=>{
    contactus.value = res.data[0]
  })
}
onMounted(() => {
  getContactUs()
})
const counter = useCounterStore()
//是否显示透明度
const scrollMain=(e)=>{
  console.log("e,",e.target.scrollTop)
  if (e.target.scrollTop < 120){
    counter.setShowOpacity(true)
  }else{
    counter.setShowOpacity(false)
  }
  if (e.target.scrollTop > 0){
    topshow.value=true
  }else{
    topshow.value=false
  }
  console.log("shjpw",topshow.value)
}
const topshow=ref(false)
const scrollToTop=()=> {
  const scrollableContent = document.getElementById('scrollableContent');
  scrollableContent.scrollTo({ top: 0, behavior: "smooth" });
}
const chatList=ref([])
const chatContent=ref()
const sendChat=()=>{
  if (!phone.value){
    ElNotification({
      title: '',
      message: "请先输入电话",
      position: 'bottom-left',
      type: 'warning',
    })
    return
  }
  if (!chatContent.value){
    ElNotification({
      title: '',
      message: "请输入内容",
      position: 'bottom-left',
      type: 'warning',
    })
    return
  }
  if (socket.value == null){
    initWebSocket()
  }
  let form={
    customerMsg:chatContent.value,
    customerPhone:phone.value
  }
  localStorage.setItem('phone',phone.value)
  save(form).then(res=>{
    if (res.code == 200){
      if (socket.value != null && socket.value.readyState !=1){
        initWebSocket()
      }
      socket.value.send(JSON.stringify(form))
      queryParams.value.page=1;
      getChatList()
      chatContent.value=''
    }
  })
}
const queryParams=ref({
  page:1,
  size:10,
  customerPhone:null,
  readType:1
})
const total=ref(0)
const getChatList=()=>{
  queryParams.value.customerPhone=localStorage.getItem('phone')
  page(queryParams.value).then(res=>{
    total.value=res.data.total
    if (queryParams.value.page == 1){
      chatList.value=res.data.list.reverse();
      nextTick(function (){
        var element = document.getElementById('scrollableDiv');
        element?.scrollTo({
          top:element.scrollHeight,
          behavior:'smooth'
        })
      });
    }else{
      chatList.value=res.data.list.reverse().concat(chatList.value)
    }
  })
}
const cancelSend=()=>{
  chatContent.value=''
}
const showChat=ref(false)
const closeChat=()=>{
  showChat.value=false
  document.getElementById('menu-btn').style.backgroundColor='ghostwhite';
  document.getElementById('menu-btn').style.color='black';
  document.getElementById('menu-btn').style.bottom='33%';
}
const openChat=()=>{
  showChat.value=!showChat.value;
  if (showChat.value){
    document.getElementById('menu-btn').style.backgroundColor='cornflowerblue';
    document.getElementById('menu-btn').style.color='white';
  }else{
    document.getElementById('menu-btn').style.backgroundColor='ghostwhite';
    document.getElementById('menu-btn').style.color='black';
  }
}
const big=ref(false)
const changeWH=(type)=>{
  if (type == 0){
    document.getElementById('chat').style.width='300px'
    document.getElementById('chat').style.height='350px'
    document.getElementById('menu-btn').style.bottom='33%';
    big.value=false
  }else if (type == 1){
    document.getElementById('chat').style.width='500px'
    document.getElementById('chat').style.height='500px'
    document.getElementById('menu-btn').style.bottom='45%';
    big.value=true
  }
}
onMounted(()=>{
  if (localStorage.getItem('phone') != undefined && localStorage.getItem('phone') != null && localStorage.getItem('phone') !='' && localStorage.getItem('phone') != "undefined"){
    getChatList()
    phone.value=localStorage.getItem('phone')
    initWebSocket()
  }else{
    chatList.value=[]
  }
  add({}).then(res=>{

  })
})
const  phone=ref()
const scrollMsg=(e)=>{
  console.log(e.target.scrollTop)
  if ( e.target.scrollTop == 0 && total.value > chatList.value.length){
    queryParams.value.page++;
    getChatList()
  }
}
const url = import.meta.env.VITE_WEBSOCKET_URL; // 替换为你的WebSocket服务器地址
const socket = ref(null);
const messages = ref([]);
const initWebSocket=()=>{
  socket.value = new WebSocket(url,[phone.value]);
  socket.value.onopen = () => {
    console.log('WebSocket Connected');
    socket.value.send("heart")
  };
  socket.value.onmessage = (event) => {
    console.log("Received message", event.data);
    if (event.data == 'ok'){
      setTimeout(function(){
        socket.value.send("heart")
      },5000)
    }else if (event.data != null && event.data != ''){
      chatList.value.push({customerServiceMsg:event.data,customerPhone:phone.value})
      nextTick(function (){
        var element = document.getElementById('scrollableDiv');
        element?.scrollTo({
          top:element.scrollHeight,
          behavior:'smooth'
        })
      });
    }
    setInterval(function(){
      if (event.data==null || event.data == '' || event.data.length == 0
      ||event.data == undefined || event.data == 'undefined'){
        console.log("接收消息2",event.data);
        initWebSocket();
      }
    },10000)
  };
  socket.value.onerror = (error) => {
    console.error('WebSocket Error:', error);
  };
  socket.value.onclose = () => {
    console.log('WebSocket Disconnected');
  };
}
const phoneChange=(e)=>{
  phone.value=e
  console.log("333",phone.value)
  localStorage.setItem('phone',phone.value)
  queryParams.value.page=1;
  getChatList()
}
const personalInfoReservationForm = ref({
  realName:'',
  phone:'',
  weixin:'',
  qq:''
})
const personalInfoReservationFormRef=ref()
const addPersonalInfoReservation=()=>{
  personalInfoReservationFormRef.value.validate((valid: any) => {
    if (valid) {
      savePersonalInfoReservation(personalInfoReservationForm.value).then(res=>{
        if (res.code == 200){
          ElMessage({
            type: 'success',
            message: '提交成功'
          })
        }
      })
    }
  });
}
const rules = reactive({
  realName: [{ required: true, message: "请输入姓名", trigger: "blur" }],
  phone: [{ required: true, message: "请输入电话", trigger: "blur" }],
});
const baseUrl=import.meta.env.VITE_API_URL;
</script>

<template>
  <div class="container">
    <el-container class="all">
      <el-header class="header">
        <Head></Head>
      </el-header>
      <el-main class="main">
        <div id="scrollableContent" class="mainDiv" style="height: 100%; overflow-y: auto;"    @scroll="scrollMain"   >
          <!-- 你的内容 -->
          <router-view>
          </router-view>
          <el-footer class="foot">
            <div class="submit">
              <h3 style="margin-bottom: 8px;text-align: center;color: grey">客户资料预留</h3>
              <el-form label-position="top" :rules="rules" ref="personalInfoReservationFormRef" :model="personalInfoReservationForm">
                <el-row :gutter="10">
                  <el-col :span="12">
                    <el-form-item label="姓名" prop="realName">
                      <el-input  style="border-radius: 5px" v-model="personalInfoReservationForm.realName"></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="手机号"  prop="phone">
                      <el-input style="border-radius: 5px" v-model="personalInfoReservationForm.phone"></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row :gutter="10">
                  <el-col :span="12">
                    <el-form-item label="微信"   prop="weixin">
                      <el-input style="border-radius: 5px"  v-model="personalInfoReservationForm.weixin"></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="QQ"   prop="qq">
                    <el-input style="border-radius: 5px" v-model="personalInfoReservationForm.qq"></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
                <div style="text-align: center;">
                  <el-button round type="primary"  @click="addPersonalInfoReservation">提交</el-button>
                </div>
              </el-form>
            </div>
            <div class="concat">
              <div class="weixindiv">
<!--                <span style="margin-bottom: 5px;">QQ联系</span>-->
                <img id="small-image" v-if="contactus && contactus.qq" :src=" baseUrl+contactus.qq" class="weixin"/>
              </div>
              <div class="weixindiv">
<!--                <span style="margin-bottom: 5px;">微信联系</span>-->
                <img  v-if="contactus && contactus.wx" :src=" baseUrl+contactus.wx"  class="weixin"/>
              </div>
            </div>
<!--            <span>版权归个人所有</span>-->
          </el-footer>
        </div>
      </el-main>
    </el-container>
    <div class="top" v-if="topshow" @click="scrollToTop">
      <el-icon><ArrowUpBold /></el-icon>
    </div>
    <div class="menu-btn" @click="openChat" id="menu-btn">
      在线咨询
    </div>
    <div class="chat" v-if="showChat" id="chat">
      <div class="chat-content" @scroll="scrollMsg" id="scrollableDiv">
        <div class="close">
          <el-icon v-if="!big" size="20" @click="changeWH(1)"><ZoomIn /></el-icon>
          <el-icon v-else size="20" @click="changeWH(0)"><ZoomOut /></el-icon>
          <el-icon size="20"  @click="closeChat"><Close></Close></el-icon>
        </div>
        <div class="chat-content-info"   v-for="item in chatList" >
          <div class="other" v-if="item.customerServiceMsg">
            <el-icon size="30">
              <svg-icon  :icon-class="'kf'" style="margin-right: 4px;"></svg-icon>
            </el-icon>
            <el-text  class="chat-text-other">{{item.customerServiceMsg}}</el-text>
          </div>
          <div class="onself" v-if="item.customerMsg">
            <el-text class="chat-text-onself" >{{item.customerMsg}}</el-text>
            <el-icon size="30">
              <svg-icon :icon-class="'defaultavatar'" style="margin-left: 4px;"></svg-icon>
            </el-icon>
          </div>
        </div>
      </div>
      <div class="send-btn">
        <div style="display: flex;flex-direction: row;align-items: center;justify-content: space-between;width: 100%">
          <el-text type="danger" style="width: 20%;text-align: center;font-weight: 550">必填</el-text><el-input style="width: 80%" size="large" placeholder="请先输入电话" v-model="phone" @change="phoneChange"></el-input>
        </div>
        <el-input size="large" type="textarea"  v-model="chatContent" placeholder="联系请留言..."/>
        <div class="send-btn-text">
          <el-button round plain type="primary" @click="sendChat">发送</el-button>
          <el-button  round plain type="warning"  @click="cancelSend">取消</el-button>
        </div>
      </div>
    </div>
  </div>
</template>
<style scoped>
.submit{
  margin-right: 25px;
}
.weixindiv{
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  text-align: center;
}
.weixin{
  border-radius: 5px;
  width: 110px;
  height: 110px;
  margin-right: 25px;
  transition: transform 0.2s;
}
.weixin:hover{
  transform: scale(2);
}

.close .el-icon{
  margin-right: 8px;
  color: gray;
}
.close .el-icon:hover{
  color: cornflowerblue;
}
.chat-text-other{
  padding: 8px;
  background-color: #e8e2e2;
  border-radius: 5px;
  width: auto;
  position: relative;
  margin-left: 5px;
}
.chat-text-onself{
  padding: 8px;background-color: #e8e2e2;border-radius: 5px;
  width: auto;
  position: relative;
  margin-right: 5px;
}
.chat-text-other::before{
  content: "";
  position: absolute;
  top: 2px; /* 根据需要调整 */
  left: -15px; /* 根据需要调整 */
  width: 0;
  height: 0;
  border-style: solid;
  border-left: 10px solid transparent;
  border-bottom: 10px solid transparent;
  border-right: 10px solid #e8e2e2;
  border-top: 10px solid transparent;
}
.chat-text-onself::before{
  content: "";
  position: absolute;
  top: 2px; /* 根据需要调整 */
  right: -15px; /* 根据需要调整 */
  width: 0;
  height: 0;
  border-style: solid;
  border-right: 10px solid transparent;
  border-bottom: 10px solid transparent;
  border-left: 10px solid #e8e2e2;
  border-top: 10px solid transparent;
}
.other{
  display: flex;
  align-items: center;
  padding: 10px 8px;
}
.onself{
  display: flex;
  align-items: center;
  justify-content: right;
  padding: 8px 10px;
}
.chat-content{
  margin-top: 25px;
  height: 60%;
  overflow: auto;
  border-top-left-radius: 5px;  /* 左上角的圆角 */
  border-top-right-radius: 5px; /* 右上角的圆角 */
}
.chat-content::-webkit-scrollbar{
  display: none;
}
.close{
  position: absolute;
  top: 4px;
  cursor: pointer;
  width: 100%;
  text-align: right;
}
.send-btn{
  height: 40%;
  background-color: #a7b8a7;
  padding: 0px 65px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: space-around;
  border-bottom-left-radius: 5px;  /* 左下角的圆角 */
  border-bottom-right-radius: 5px; /* 右下角的圆角 */
  overflow: auto;
}
.send-btn::-webkit-scrollbar{
  display: none;
}
.send-btn-text{
  display: flex;
  align-items: center;
  justify-content: right;
  width: 100%;
}
::v-deep(.el-main){
  --el-main-padding: 0px !important;
}
.all{
  position: relative;
}
.mainDiv::-webkit-scrollbar{
  display: none;
}
.foot{
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #d6d6d6;
  color: darkgray;
  padding: 25px;
  height: auto;
}
.header{
  //background-color: #eee;
  height: 10vh;
  padding-left: 0px;
  padding-right: 0px;
  position:absolute;
  top:0;
  width:100%;
  z-index:1;
}
.main{
  background-color: #fff;
  height: 100vh;
  width: 100%;
}
.top{
  position: absolute;
  right: 50px;
  bottom: 35px;
  width: 40px;
  height: 40px;
  background-color: ghostwhite;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 5px;
  cursor: pointer;
}
.top:hover{
  border-radius: 50%;
  box-shadow: 0 8px 12px 0 rgba(0,0,0,0.2);
}
.chat{
  position: absolute;
  left: 50px;
  bottom: 4%;
  width:300px;
  height:350px;
  border-radius: 5px;
  background-color: white;
  box-shadow: 0px 8px 12px 9px rgba(0,0,0,0.2);
}
.menu-btn{
  position: absolute;
  left: 50px;
  bottom: 33%;
  width:50px;
  height:50px                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         ;
  padding: 10px;
  border-radius: 50%;
  background-color: ghostwhite;
  color: black;
  font-size: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  text-align: center;
  box-shadow: 1px 1px 5px antiquewhite;
  font-weight: 500;
  cursor: pointer;
}
.concat{
  display: flex;
  flex-direction: row;
}
@media (max-width: 865px) {
  .weixin{
    width: 90px;
    height: 90px;
  }
  .foot{
    font-size: 12px;
    flex-direction: column;
    padding: 10px;
  }
  .concat{
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: center;
    margin-top: 8px;
  }
}
</style>
